<?php
#### POPUP LOGIN FORM ##########################################################
function popupLoginForm($ajax_url, $login_url = FALSE, $logout_url = 'logout') {
	$base =& Base::getInstance();

	$login_url= $base->config['url'].$login_url;
	$logout_url= $base->config['url'].$logout_url;

	variable($request, 'post', 'request');
	$logged_in = FALSE;

	if (isset($request['username'])) {
		if (empty($request['password'])) $feedback = notice('Please enter a password.', 'error');
		if (empty($request['username'])) $feedback = notice('Please enter a username.', 'error');

		else if ($request['username'] && $request['password']) {
			$base->session->username = $request['username'];
			$base->session->password = $request['password'];
			$base->session->remember = $request['remember'];
			if ($base->session->login()) {
				$logged_in = TRUE;
				$feedback = notice('Yay, We have logged you in!.');
				echo '<script type="text/javascript">
					setTimeout("$.hidePopup()", 1500);
				</script>';
				echo redirect($login_url, TRUE, 2000);
			}
			else $feedback = notice('Oops, looks like you\'ve entered the wrong things!', 'error');
		}
	}

	if (!isset($request['username']) && $base->sessvar['login']['username']) {
		$logged_in = TRUE;
		$feedback = notice('Hey you\'re already logged in?! <a id="logout" href="'.$logout_url.'"><b>Logout?</b></a>', 'error');

		echo '<script type="text/javascript">
			$(document).ready(function() {
				$("#logout").click(function(e) {
       				e.preventDefault();
					$.hidePopup();
					setTimeout("window.location = \''.$logout_url.'\'", 500);
				})
			});
		</script>';
	}

	echo '<script type="text/javascript">
	$(function() {
		$("#post").submit(function() {
			var inputs = [];
			$(":input", this).each(function() {
				inputs.push(this.name + "=" + escape(this.value));
			})

			$("#popup-area").load("'.$ajax_url.'", $("#post").serialize());
			return false;
		})
	})
	</script>';

	echo '<h2>Please Login</h2>
	<hr />';
	if (isset($feedback)) echo $feedback;
	else echo notice('<a href="users/register">Need an account?</a> or <a href="users/forgotten-password">Forgotten your password?</a>', 'info');

	if (!$logged_in) {
		$form = $base->load->library('form');

		$form->validate('username', 'alnum');
		$form->validate('password', 'alnum');

		$form->open();
		$form->openFieldset('Login');
		$form->text('Username', 'username', $request['username'], NULL, 23);
		$form->password('Password', 'password', NULL, NULL, 23);
		$form->checkbox('Remember Login', 'remember', $request['remember']);
		$form->button('submit', 'Submit');
		$form->closeFieldset('Login');
		$form->close();
		echo $form->output();
	}

	// Prevent further code excution
	die();
}
?>